FROM debian:trixie-slim AS builder

# Build args
ARG YAMS_VERSION=dev
ARG GIT_COMMIT=""
ARG GIT_TAG=""

# Base toolchain + headers
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential git curl pkg-config ca-certificates \
    libssl-dev libsqlite3-dev protobuf-compiler libprotobuf-dev \
    python3 python3-venv python3-pip \
    gcc-13 g++-13 \
    && rm -rf /var/lib/apt/lists/*

# Python toolchain in a venv (bypass PEP 668) + pin versions
RUN python3 -m venv /opt/venv \
    && /opt/venv/bin/pip install --upgrade pip \
    && /opt/venv/bin/pip install "conan==2.3.*" "cmake==3.27.*" "ninja==1.11.*"
ENV PATH="/opt/venv/bin:${PATH}"

# Force GCC 13 so Conan detects a supported compiler.version
ENV CC=/usr/bin/gcc-13
ENV CXX=/usr/bin/g++-13

WORKDIR /src
COPY . .

# Conan profile (C++20), generated by conanfile (no -g flags here)
RUN conan profile detect --force \
    && sed -i 's/compiler.cppstd=.*/compiler.cppstd=20/' ~/.conan2/profiles/default \
    && conan profile show

# Install deps; static to reduce runtime deps
RUN conan install . \
    --output-folder=build/conan-release \
    -s build_type=Release \
    --build=missing \
    -o "*:shared=False" \
    -o "boost/*:without_locale=True" \
    -o "boost/*:without_stacktrace=True" \
    -c tools.cmake.cmaketoolchain:generator=Ninja

# Compute a semver for CMake and an optional suffix for runtime info
# - If GIT_TAG looks like vMAJOR.MINOR.PATCH, use that (strip leading v)
# - Else use 0.0.0 and keep a dev suffix with the short commit
RUN if printf '%s' "${GIT_TAG}" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then \
    CMAKE_VERSION="${GIT_TAG#v}"; \
    VERSION_SUFFIX=""; \
    else \
    CMAKE_VERSION="0.0.0"; \
    VERSION_SUFFIX="dev-${GIT_COMMIT}"; \
    fi && \
    cmake --preset conan-release \
    -DYAMS_BUILD_PROFILE=release \
    -DYAMS_BUILD_DOCS=OFF \
    -DYAMS_BUILD_TESTS=OFF \
    -DYAMS_BUILD_MCP_SERVER=ON \
    -DYAMS_VERSION="${CMAKE_VERSION}" \
    -DYAMS_VERSION_SUFFIX="${VERSION_SUFFIX}" && \
    cmake --build --preset conan-release --parallel

RUN cmake --install build/conan-release/build/Release --prefix /opt/yams

FROM debian:trixie-slim AS runtime
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

RUN groupadd -r yams && useradd -r -g yams -s /bin/false yams
COPY --from=builder /opt/yams/bin/yams /usr/local/bin/yams
COPY --from=builder /src/data/magic_numbers.json /usr/local/share/yams/data
RUN mkdir -p /home/yams/.local/share/yams /home/yams/.config/yams && chown -R yams:yams /home/yams
USER yams
WORKDIR /home/yams
ENV YAMS_STORAGE="/home/yams/.local/share/yams" \
    XDG_DATA_HOME="/home/yams/.local/share" \
    XDG_CONFIG_HOME="/home/yams/.config"
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD yams --version || exit 1
ENTRYPOINT ["yams"]
CMD ["--help"]
